import re
import time
import hashlib
import datetime
import urllib.parse


def md5sum(src):
    m = hashlib.md5()
    m.update(src.encode('utf-8'))
    return m.hexdigest()


# 鉴权方式A
def a_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    rand = "0"  # "0" by default, other value is ok
    uid = "0"  # "0" by default, other value is ok
    sstring = "%s-%s-%s-%s-%s" % (path, exp, rand, uid, key)
    hashvalue = md5sum(sstring)
    auth_key = "%s-%s-%s-%s" % (exp, rand, uid, hashvalue)
    if args:
        return "%s%s%s%s&auth_key=%s" % (scheme, host, path, args, auth_key)
    else:
        return "%s%s%s%s?auth_key=%s" % (scheme, host, path, args, auth_key)


# 鉴权方式B
def b_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    # convert unix timestamp to "YYmmDDHHMM" format
    nexp = datetime.datetime.fromtimestamp(exp).strftime('%Y%m%d%H%M')
    sstring = key + nexp + path
    hashvalue = md5sum(sstring)
    return "%s%s/%s/%s%s%s" % (scheme, host, nexp, hashvalue, path, args)


# 鉴权方式C
def c_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    hexexp = "%x" % exp
    sstring = key + path + hexexp
    hashvalue = md5sum(sstring)
    return "%s%s/%s/%s%s%s" % (scheme, host, hashvalue, hexexp, path, args)


def main():
    #uri = "http://ossfile.zdiai.net/" + urllib.parse.quote("阿里云20200101-20201031费用详单.csv")  # original uri
    file_name = "佩奇.jpg"
    uri = "http://ossfile.zdiai.net/" + urllib.parse.quote(file_name)  # original uri
    key = "BEFB64DB816F439EAA25DEB6432299F7"  # private key of authorization
    exp = int(time.time()) + 1 * 3600  # expiration time: 1 hour after current itme
    authuri = a_auth(uri, key, exp)  # auth type: a_auth / b_auth / c_auth
    print("URL : %s\nAUTH: %s" % (uri, authuri))


if __name__ == "__main__":
    main()
